package com.coolrui.domain.order.repository.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coolrui.common.system.ApiList;
import com.coolrui.common.utils.CommonUtils;
import com.coolrui.domain.order.entity.UserOrder;
import com.coolrui.domain.order.mapper.UserOrderMapper;
import com.coolrui.domain.order.repository.UserOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public class UserOrderRepositoryImpl implements UserOrderRepository {
    @Autowired
    private UserOrderMapper userOrderMapper;

    @Override
    public int createOrder(UserOrder userOrder) {
        // 实现保存逻辑
        return userOrderMapper.insert(userOrder);
    }

    @Override
    public Optional<UserOrder> findByOrderId(Long orderId) {
        //自定义XML方法，根据订单ID查询
        return Optional.ofNullable(userOrderMapper.findByOrderId(orderId));
    }

    @Override
    public UserOrder getOrder(Long orderId) {
        return userOrderMapper.selectById(orderId);
    }

    /**
     * 分页查找用户订单列表
     * @param userId 用户ID
     * @param page 页码
     * @param pageSize 每页订单条数
     * @return 订单列表
     */
    @Override
    public ApiList<UserOrder> getOrderList(Long userId, Integer page, Integer pageSize) {
        LambdaQueryWrapper<UserOrder> wrapper = Wrappers.lambdaQuery();
        //根据条件查询
        wrapper.eq(UserOrder::getUserId, userId);
        //设置分页SQL
        wrapper.last(CommonUtils.getLimitSql(page, pageSize,true));
        //执行查询
        List<UserOrder> list = userOrderMapper.selectList(wrapper);
        //API接口优化：是否存在下一页
        boolean hasMore = list.size() > pageSize;
        if (hasMore) {
            list = ListUtil.sub(list, 0, pageSize);
        }
        return ApiList.makeResult(hasMore, list);
    }

    @Override
    public int updateOrder(Long orderId, UserOrder userOrder) {
        // 使用 LambdaUpdateWrapper 指定条件
        LambdaUpdateWrapper<UserOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserOrder::getOrderId, orderId);

        return userOrderMapper.update(userOrder, wrapper);
    }
}